<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="isAvailable" slot-scope="{ row }">
        <el-switch
          v-model="row.isAvailable"
          active-color="#ff4949"
          inactive-color="#999"
          :active-value="1"
          :inactive-value="0"
          @change="changeIsAvailable(row)"
          active-text="启用"
          inactive-text="禁用"
        >
        </el-switch>
      </template>
      <template slot="menuLeft">
        <el-button
          type="primary"
          size="small"
          icon="el-icon-delete"
          v-if="permission.userstaff_delete"
          @click="handleDelete"
          >删除员工
        </el-button>
        <el-button
          type="primary"
          size="small"
          v-if="permission.userstaff_delete"
          @click="progressive"
          >批量档位递进
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  progressive,
  getPostList,
  getDutyList,
} from "@/api/configure/userstaff";
import { mapGetters } from "vuex";
import axios from "axios";
export default {
  data() {
    return {
      postList: [],
      dutyList: [],
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      data: [],
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.userstaff_add, false),
        viewBtn: this.vaildData(this.permission.userstaff_view, false),
        delBtn: this.vaildData(this.permission.userstaff_delete, false),
        editBtn: this.vaildData(this.permission.userstaff_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    option() {
      return {
        align: "center",
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        selection: true,
        dialogClickModal: false,
        addBtnText: "新增员工",
        editBtnText: "信息维护",
        delBtn: false,
        labelPosition: "left",
        column: [
          {
            label: "员工编号",
            prop: "code",
          },
          {
            label: "员工姓名",
            prop: "realName",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入员工姓名",
                trigger: "blur",
              },
            ],
          },
          {
            label: "性别",
            prop: "sex",
            type: "select",
            dicData: [
              {
                label: "男",
                value: 1,
              },
              {
                label: "女",
                value: 2,
              },
            ],
            rules: [
              {
                required: true,
                message: "请输入性别",
                trigger: "blur",
              },
            ],
          },
          {
            label: "身份证号",
            prop: "idCard",
            rules: [
              {
                required: true,
                message: "请输入身份证号",
                trigger: "blur",
              },
              // {
              //   pattern:
              //     /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
              //   message: "请输入正确的身份证号码",
              //   trigger: "blur",
              // },
            ],
          },
          {
            label: "所属组织",
            prop: "deptId",
            type: "tree",
            search: true,
            props: {
              label: "title",
              value: "id",
            },
            dicUrl: `/api/fine-system/dept/tree`,
            dicFormatter: (res) => {
              return res.data;
            },
            rules: [
              {
                required: true,
                message: "请输入所属组织",
                trigger: "blur",
              },
            ],
          },
          {
            label: "联系电话",
            prop: "phone",
          },
          {
            label: "岗位",
            prop: "postId",
            type: "select",
            props: {
              label: "postName",
              value: "id",
            },
            dicUrl: `/api/fine-system/post/list4dict`,
            dicFormatter: (res) => {
              return res.data;
            },
            change: (v) => {
              if (!v.value) return;
              let item = this.postList.filter((ele) => {
                return ele.id == v.value;
              })[0];
              if (item && item.wages > this.form.postWages) {
                this.form.postWages = item.wages;
              }
            },
            rules: [
              {
                required: true,
                message: "请选择岗位",
                trigger: "blur",
              },
            ],
          },
          {
            label: "职务",
            prop: "dutiesId",
            type: "select",
            props: {
              label: "dutiesName",
              value: "id",
            },
            dicUrl: `/api/fine-configure/duties/list4dict`,
            dicFormatter: (res) => {
              return res.data;
            },
            change: (v) => {
              if (!v.value) return;
              let item = this.dutyList.filter((ele) => {
                return ele.id == v.value;
              })[0];
              if (item && item.wages > this.form.postWages) {
                this.form.postWages = item.wages;
              }
            },
            // rules: [
            //   {
            //     required: true,
            //     message: "请选择职务",
            //     trigger: "blur",
            //   },
            // ],
          },
          {
            label: "岗位/职务工资",
            prop: "postWages",
            labelWidth: 120,
            value: 0,
            rules: [
              {
                required: true,
                message: "请输入岗位/职务工资",
                trigger: "blur",
              },
              {
                pattern: /^(([0-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
                message: "岗位/职务工资必须大于0且只能保留两位小数",
                trigger: "blur",
              },
            ],
          },
          {
            label: "工资保障",
            prop: "protection",
            type: "select",
            dicUrl: "/api/fine-system/dict/dictionary?code=guarantee",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "number",
            // rules: [
            //   {
            //     required: true,
            //     message: "请选择工资保障",
            //     trigger: "blur",
            //   },
            // ],
          },
          {
            label: "是否评级",
            prop: "isGrading",
            type: "select",
            value: 1,
            dicData: [
              {
                label: "否",
                value: 0,
              },
              {
                label: "是",
                value: 1,
              },
            ],
            dataType: "number",
            rules: [
              {
                required: true,
                message: "请输入是否评级",
                trigger: "blur",
              },
            ],
          },
          {
            label: "套改等级",
            prop: "levelId",
            type: "select",
            search: true,
            props: {
              label: "levelInfoName",
              value: "id",
            },
            dicUrl: `/api/fine-configure/levelinfo/list4dict`,
            dicFormatter: (res) => {
              return res.data;
            },
            disabled: this.form.isGrading == 0 ? true : false,
          },
          {
            label: "开户银行",
            prop: "bank",
            showColumn: false,
            // rules: [
            //   {
            //     required: true,
            //     message: "请输入开户银行",
            //     trigger: "blur",
            //   },
            // ],
          },
          {
            label: "银行卡号",
            prop: "bankNumber",
            rules: [
              {
                required: true,
                message: "请输入银行卡号",
                trigger: "blur",
              },
            ],
          },
          {
            label: "状态",
            prop: "isAvailable",
            type: "switch",
            width: 160,
            value: 1,
            dicData: [
              {
                label: "禁用",
                value: 0,
              },
              {
                label: "启用",
                value: 1,
              },
            ],
            dataType: "number",
            // rules: [
            //   {
            //     required: true,
            //     message: "请选择是否评级",
            //     trigger: "blur",
            //   },
            // ],
          },
          // {
          //   label: "时间",
          //   prop: "date",
          //   type: "datetimerange",
          //   format: "yyyy-MM-dd HH:mm:ss",
          //   valueFormat: "yyyy-MM-dd HH:mm:ss",
          //   defaultTime: ["00:00:00", "23:59:59"],
          //   startPlaceholder: "入职时间",
          //   endPlaceholder: "离职时间",
          //   showColumn: false,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请选择入职时间和离职时间",
          //       trigger: "blur",
          //     },
          //   ],
          // },
          {
            label: "入职时间",
            prop: "joinTime",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            // addDisplay: false,
            // editDisplay: false,
          },
          {
            label: "离职时间",
            prop: "outTime",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            // addDisplay: false,
            // editDisplay: false,
          },
        ],
      };
    },
  },
  mounted() {
    this.loading = true;
    axios.all([getPostList(), getDutyList()]).then(
      axios.spread((acct, perms) => {
        this.$nextTick(() => {
          this.postList = acct.data.data;
          this.dutyList = perms.data.data;
          this.loading = false;
        });
      })
    );
  },
  methods: {
    changeIsAvailable(row) {
      let data = {
        id: row.id,
        isAvailable: row.isAvailable,
      };
      update(data).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!",
        });
      });
    },
    rowSave(row, done, loading) {
      // row.joinTime = row.date[0];
      // row.outTime = row.date[1];
      // delete row.date;
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      // row.joinTime = row.date[0];
      // row.outTime = row.date[1];
      // delete row.date;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    progressive() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      progressive(this.ids).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!",
        });
        this.$refs.crud.toggleSelection();
      });
    },
    deleteEmptyProperty(obj) {
      for (let i in obj) {
        let value = obj[i];
        if (typeof value === "object") {
          if (Array.isArray(value)) {
            if (value.length == 0) {
              obj[i] = "";
              continue;
            }
          }
          this.deleteEmptyProperty(value);
        } else {
          if (value === undefined || value === -1) {
            obj[i] = "";
          }
        }
      }
      return obj;
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = this.deleteEmptyProperty(res.data.data);
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        data.records.forEach((ele) => {
          ele = this.deleteEmptyProperty(ele);
        });
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style></style>
